import React, { Component } from 'react'
import { Button, Drawer, Alert, Divider, Modal, Upload, Icon } from 'antd';
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout'
import { TableCustomize, BasicPagination, openModalMessage, openSuccessModal, compareNum } from '../../../components/TableCustomize'
import AddForm from './AddForm';
import SearchForm from './SearchForm'
import { baseUrl, toLead } from '../../../config';
import * as APIService from '../../../axios/api_yq'
import { withPermission } from '../../../components/withpermission'
const CreateButton = withPermission(Button, 'plus')
const DeleteButton = withPermission(Button, 'line')
const DownLoadButton = withPermission(Button, 'download')
const UploadButton = withPermission(Button, 'upload')

const { confirm } = Modal;
export default class Maintain extends Component {
    state = {
        dataSource: [
        ],
        inquire: [],
        paging: {},
        visible: false,
        formData: {},
        drawerVisible: false,
        drawerTitle: '',
        createTime: null,
        one: false,
        loading: false,
        some: null,
        selectedRows: [],
        selectedRowKeys: [],
        advanced: false,
        values: {},
        control: false,
        buttonList: [],
        CalssData: null,
        buttonLoading: false
    }
    // 挂载前
    UNSAFE_componentWillMount() {
        this.fetch();
    }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    //初始化加载数据
    fetch = (page = 1, size = 100) => {
        const { values } = this.state
        const buttonList = JSON.parse(localStorage.getItem('buttonList'))
        // console.log('这是按钮', buttonList);
        if (buttonList ? buttonList.length !== 0 : null) {
            this.setState({
                buttonList
            })
        }
        this.setState({
            loading: true,
            paging: { pageNum: page, pageSize: size }
        })
        let a = { pageNum: page, pageSize: size }
        setTimeout(() => {
            this.search({ ...values, ...a })
        }, 300);
    }
    // 查询接口
    search = (value) => {
        APIService.queryByCondition1(value).then((item) => {
            if (item.data.code === 200) {
                this.setState({
                    dataSource: item.data.data.data,
                    // 操作后清除选中
                    selectedRowKeys: [],
                    selectedRows: [],
                    some: null,
                    loading: false,
                    paging: {
                        pageNum: item.data.data.pageNum,
                        pageSize: item.data.data.pageSize,
                        total: item.data.data.total,
                    }
                })
            } else {
                openModalMessage('error', item.data.msg)
            }
        })
    }
    // 新增、修改接口
    addModification = (data) => {
        const { values, paging } = this.state
        APIService.alterOrAddProduct(data).then((item) => {
            if (item.data.code === 200) {
                openSuccessModal(item.data.msg)
                this.handleCancel()
                this.search({ ...values, ...paging })
                this.setState({
                    formData: {}
                })
            } else {
                this.setState({
                    buttonLoading: false
                })
                openModalMessage('error', item.data.msg)
            }
        })
    }
    // 当前行获得数据
    deleteRow1 = (b) => {
        APIService.addGroup().then((value) => {
            let data = value.data.data
            this.setState({
                one: true,
                drawerVisible: true,
                formData: b,
                drawerTitle: '编辑',
                CalssData: data
            });
        })
    }
    // 单行删除
    deleteRow2 = (c) => {
        const then = this
        const { values, paging } = this.state
        let ids = { ids: [c.id] }
        confirm({
            title: '确认删除当项吗，这将影响其他数据模块?',
            onOk() {
                APIService.deleteProduct1(ids).then((item) => {
                    if (item.data.code === 200) {
                        openSuccessModal('删除成功')
                        then.search({ ...values, ...paging })
                    } else {
                        openModalMessage('error', '删除失败')
                    }
                })
            },
            onCancel() {
            },
        })
    }
    // 新增数据/修改
    onHandleOk = () => {
        const { formData } = this.state
        // console.log(formData.id);
        let id = formData.id
        this.formDrawer.validateFields((err, value) => {
            if (err) return;
            let amend = { ...value, id }
            // console.log('数据', amend);
            this.setState({
                buttonLoading: true
            }, () => {
                this.addModification(amend)
            })

        })
    }
    // 取消
    handleCancel = e => {            //表单重置函数
        this.formAdd && this.formAdd.resetFields();
        this.formDrawer && this.formDrawer.resetFields();
        this.setState({
            visible: false,
            drawerVisible: false,
            one: false,
            formData: {},
            buttonLoading: false
        });
    };
    // 条件查询查询
    handleSearch = value => {
        const { paging, values } = this.state
        let a = { pageNum: paging.pageNum, pageSize: paging.pageSize }
        this.setState({
            values: value
        })
        this.search({ ...value, ...a })
    };
    // 编辑行数据
    loadData = (value, dataSource) => {
        console.log('这是编辑行接收的数据', value, dataSource)
        this.addModification(value)
    }
    //0新增
    create = () => {
        APIService.addGroup().then((value) => {
            console.log(value);
            let data = value.data.data
            this.setState({
                one: false,
                drawerVisible: true,
                drawerTitle: '新增',
                CalssData: data
            });
        })
    };
    //删除选中
    remove = () => {
        const { selectedRows, some, values, paging } = this.state
        let a = [...selectedRows]
        let b = []
        a.forEach(item => {
            b.push(item.id)
        })
        let ids = { ids: b }
        if (some > 0) {
            APIService.deleteProduct1(ids).then((item) => {
                if (item.data.code === 200) {
                    openSuccessModal('删除成功')
                    this.search({ ...values, ...paging })
                } else {
                    openModalMessage('error', '删除失败')
                }
            })
        } else {
            openModalMessage('error', '请选择数据')
        }

    }
    // 导出模板
    derive = () => {
        APIService.exportProductDemo().then(res => {
            console.log(res);
            //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
            let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
            // 创建A标签
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            // 设置的下载文件文件名
            const fileName = decodeURI('产品维护');
            // 触发点击方法
            link.setAttribute('download', fileName)
            document.body.appendChild(link)
            link.click()
        })
    }
    // 导出选中
    derive1 = () => {
        const { selectedRows, some } = this.state
        // 拿到的数据
        let selectedRowss = [...selectedRows]
        console.log(selectedRowss);
        let a = {
            list: [
                ...selectedRowss
            ]
        }
        if (some > 0 && some !== null && some !== 0) {
            APIService.exportProduct(a).then(res => {
                console.log(res);
                //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
                let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
                // 创建A标签
                let link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                // 设置的下载文件文件名
                const fileName = decodeURI('产品维护');
                // 触发点击方法
                link.setAttribute('download', fileName)
                document.body.appendChild(link)
                link.click()
            })
        } else {
            openModalMessage('error', '请选中导出项')
        }
    }
    // 重置
    cz = () => {
        this.setState({
            values: null
        }, () => { this.fetch() })

    }
    // 高级查询
    advancedss = () => {
        // console.log('高级查询');
        this.setState({ advanced: !this.state.advanced })
    }
    // 按钮点击事件
    // btnClick = (a) => {
    //     if (a === 0) {
    //         this.create()
    //     }
    //     if (a === 1) {
    //         this.remove()
    //     }
    //     if (a === 2) {
    //         this.derive()
    //     }
    //     if (a === 3) {
    //         this.derive1()
    //     }
    // }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    render() {
        const then = this
        const { CalssData, buttonLoading, buttonList, control, selectedRowKeys, advanced, some, one, paging, loading, dataSource, formData, drawerVisible, drawerTitle } = this.state;
        const rowSelection = {
            type: 'checkbox',
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                let some = [...selectedRows].length
                this.setState({
                    some: some,
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys
                }, () => {
                    console.log('选中个数', this.state.some, '选中详细数据', this.state.selectedRows);
                })
                if (some === 0 || some === null) {
                    this.setState({
                        control: false
                    })
                } else {
                    this.setState({
                        control: true
                    })
                }
            },
        }
        const columns = [
            {
                title: '序号',
                dataIndex: 'number',
                width: 50,
                align: 'center',
                render: (text, record, index) =>
                    <div>
                        {index + 1}
                    </div>
            },
            {
                title: '一类车间',
                width: 100,
                dataIndex: 'attributeFirst',
                sorter: (a, b) => compareNum(a.attributeFirst, b.attributeFirst),
            },
            {
                title: '二类分类',
                width: 100,
                dataIndex: 'attributeSecond',
                sorter: (a, b) => compareNum(a.attributeSecond, b.attributeSecond),
            },
            {
                title: '工厂',
                width: 100,
                dataIndex: 'factory'
            },
            {
                title: '机型',
                width: 100,
                dataIndex: 'code',
                sorter: (a, b) => compareNum(a.code, b.code),
            },
            {
                title: '加工部门',
                width: 100,
                dataIndex: 'assemblyWorker',
                sorter: (a, b) => compareNum(a.assemblyWorker, b.assemblyWorker),
            },
            {
                title: '附加信息1',
                width: 120,
                dataIndex: 'otherMsg1',
                editable: true,
                sorter: (a, b) => compareNum(a.otherMsg1, b.otherMsg1),
            },
            {
                title: '附加信息2',
                width: 120,
                dataIndex: 'otherMsg2',
                editable: true,
                sorter: (a, b) => compareNum(a.otherMsg2, b.otherMsg2),
            },
            {
                title: '操作',
                dataIndex: 'opts',
                width: 100,
                render:
                    (text, record) =>
                        <div>
                            <a onClick={this.deleteRow1.bind(this, record)}>{'编辑'}</a>
                            <Divider type="vertical" />
                            <a onClick={this.deleteRow2.bind(this, record)}>{'删除'}</a>
                        </div>
            },
            { dataIndex: '' }
        ]
        // 导入
        const propss = {
            name: 'file',
            action: `${baseUrl}${toLead}/product/importProductExcel`,
            accept: '.xls,.xlsx',
            method: 'post',
            showUploadList: true,
            headers: {
                userId: localStorage.getItem('userId'),
                Token: localStorage.getItem('token'),
            },
            onChange(info) {
                console.log('这是', info);
                if (info.file.status !== 'uploading') {
                    console.log('这是什么', info.file, info.fileList);
                }
                if (info.file.status === 'done') {
                    openSuccessModal('导入成功')
                    then.fetch()
                } else if (info.file.status === 'error') {
                    openModalMessage('error', '错误')
                }
            },
        }
        return (
            <div>
                <BasicLayoutSearch>
                    <SearchForm
                        onSearch={this.handleSearch}
                        onClick={this.cz}
                        onClick1={this.advancedss}
                        advanced={advanced}
                    />
                </BasicLayoutSearch>
                {
                    control === true ? <Alert message={<div>已选择 <span style={{ color: '#1890ff' }}>{some}</span> 项</div>} type="info" showIcon style={{ width: '99%', margin: 'auto' }} /> : null
                }

                <BasicLayout
                    name="产品维护"
                    icon="table"
                    buttons={[
                        <CreateButton key={1} onClick={this.create} icon="plus" />,
                        <DeleteButton key={2} onClick={this.remove} icon="delete" />,
                        <DownLoadButton key={3} onClick={this.derive} icon="download" text="模板导出" />,
                        <DownLoadButton key={4} onClick={this.derive1} icon="download" text="导出选中" />,
                        <Upload {...propss} key={6}>
                            <UploadButton icon='upload' />
                        </Upload>,

                        // <Button key={1} onClick={this.create} type="primary" icon='plus'>新增</Button>,
                        // <Button key={2} onClick={this.remove} type="primary" icon='line'>删除</Button>,
                        // <Button key={3} onClick={this.derive} type="primary" icon='download'>模板导出</Button>,
                        // <Button key={4} onClick={this.derive1} type="primary" icon='download'>导出选中</Button>,
                        // <Upload {...propss} key={5}>
                        //     <Button type="primary">
                        //         <Icon type="upload" /> 导入
                        //     </Button>
                        // </Upload>,
                    ]}
                >
                    <TableCustomize
                        rowSelection={rowSelection}
                        columns={columns}
                        rowKey={(record) => record.id}
                        dataSource={dataSource}
                        pagination={false}
                        loading={loading}
                        allowDrafting={true}
                        allowEditable={this.loadData}
                        scroll={{ x: true, y: 600 }}
                        rowClassName={(record, index) => {
                            return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
                        }}
                    />
                    <BasicPagination pageNum={paging.pageNum} pageSize={paging.pageSize} total={paging.total} loadData={this.fetch} />
                </BasicLayout>
                <Drawer width={500} visible={drawerVisible} title={drawerTitle} onClose={this.handleCancel} destroyOnClose>
                    <AddForm
                        formData={formData}
                        one={one}
                        onOk={this.onHandleOk}
                        onClose={this.handleCancel}
                        ref={node => (this.formDrawer = node)}
                        CalssData={CalssData}
                    />
                    <div
                        style={{
                            position: 'absolute',
                            right: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button onClick={this.handleCancel} style={{ marginRight: 10 }}>{'取消'}</Button>
                        <Button type="primary" onClick={this.onHandleOk} loading={buttonLoading}>
                            {'确认'}
                        </Button>
                    </div>
                </Drawer>
            </div>
        )
    }
}
